package com.pc.cloud.recommend.stat;

import com.pc.cloud.services.QueryBuilder;
import com.pc.cloud.services.SearchArgs;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.util.Version;


public class StatQueryBuilder implements QueryBuilder {
	private static StatQueryBuilder builder;
    QueryParser parser = new QueryParser(Version.LUCENE_30,"content",new SimpleAnalyzer());
	private StatQueryBuilder() {
	}

	public synchronized static StatQueryBuilder getInstance() {
		if (builder != null) {
			return builder;
		} else {
			builder = new StatQueryBuilder();
			return builder;
		}
	}

	public Query buildQuery(SearchArgs searchArgs) throws Exception {
		StatSearchArgs keywordSearchArgs = (StatSearchArgs) searchArgs;
		BooleanQuery resultQuery = new BooleanQuery();

		if (resultQuery.clauses().size() <= 0) {
			resultQuery.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
		}
		return resultQuery;
	}

	public Query buildFilter(SearchArgs args) throws Exception {
		StatSearchArgs statSearchArgs = (StatSearchArgs) args;
		BooleanQuery resultQuery = new BooleanQuery();

		this.filterByKeyword(statSearchArgs, resultQuery);

		// this.filterById(keywordSearchArgs,resultQuery);

		/*Filter filter = null;
		if (resultQuery.clauses().size() > 0) {
			filter = new QueryWrapperFilter(resultQuery);
		}*/

		return resultQuery;
	}

	private void filterByKeyword(StatSearchArgs statSearchArgs,
			BooleanQuery resultQuery) {
		if (StringUtils.isNotBlank(statSearchArgs.getKeyword())) { 
        	Query query = new TermQuery(new Term(StatSearchFields.Keyword.KEYWROD_UNTOKENIZIED,statSearchArgs.getKeyword()));
			resultQuery.add(query, BooleanClause.Occur.MUST);        	
        }

	}

	public Sort buildSort(SearchArgs args) throws Exception {
		Sort sort = null;
		if (args.getSortFields() != null) {
			sort = new Sort(args.getSortFields());
		}
		return sort;
	}

}
